import axios from 'axios';
import { BASE_URL } from '@/constants/api';
import router from '@/router';

const req = axios.create({
  baseURL: BASE_URL,
  method: 'GET',
});

// 请求拦截(加token)
req.interceptors.request.use(
  (config) => {
    return {
      ...config,
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token'),
      },   
    };
  },
);

// 响应拦截(判断401 跳页面)
req.interceptors.response.use(
  // 响应成功
  res => res,
  // 响应失败
  err => {
    const code = err.response.status;
    switch (code) {
      case 401:
        router.push('/login');
        break;
      default:
        break;
    }
    return err;   
  },
);

export default req;